/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
 *  Copyright 2008 Global Sign In
 * 
 *  This code is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <stdlib.h>
#include <vector>
#include <iostream>
#include <utility>

#include "CampaignSQL.h"
#include "ConfigurationFile.h"
#include "StatusUpdater.h"

using std::clog;
using std::endl;
using std::string;
using std::set;
using std::map;
using std::multimap;
using std::vector;
using std::pair;

static string getDomainName(const string &emailAddress)
{
	string domainName;

	string::size_type atPos = emailAddress.find('@');
	if ((atPos != string::npos) &&
		(atPos + 1 < emailAddress.length()))
	{
		domainName = emailAddress.substr(atPos + 1);
	}

	return domainName;
}

CampaignSQL::CampaignSQL(MySQLBase *pDb) :
	m_pDb(pDb)
{
}

CampaignSQL::~CampaignSQL()
{
}

bool CampaignSQL::createNewCampaign(Campaign &campaign,
	MessageDetails *pDetails)
{
	if ((m_pDb == NULL) ||
		(campaign.m_name.empty() == true) ||
		(campaign.hasValidStatus() == false) ||
		(pDetails == NULL))
	{
		return false;
	}

	string insertSql("INSERT INTO evaa_emailcampaign (evaa_emailcampaignid, "
		"name, status, subject, fromname, fromemail, replyname, replyemail, timestamp, "
		"senderemail, unsublink) VALUES(DEFAULT, '");
	insertSql += m_pDb->escapeString(campaign.m_name);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(campaign.m_status);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(pDetails->m_subject);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(pDetails->m_fromName);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(pDetails->m_fromEmailAddress);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(pDetails->m_replyToName);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(pDetails->m_replyToEmailAddress);
	insertSql += "', UNIX_TIMESTAMP(), '";
	insertSql += m_pDb->escapeString(pDetails->m_senderEmailAddress);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(pDetails->m_unsubscribeLink);
	insertSql += "');";

	if (m_pDb->executeSimpleStatement(insertSql, campaign.m_id) == true)
	{
		return true;
	}

	return false;
}

Campaign *CampaignSQL::getCampaign(const string &campaignId)
{
	if ((m_pDb == NULL) ||
		(campaignId.empty() == true))
	{
		return NULL;
	}

	MySQLResults *pCampaignResults = m_pDb->executeStatement("SELECT "
		"evaa_emailcampaignid, name, status FROM evaa_emailcampaign "
		"WHERE evaa_emailcampaignid='%s';",
		campaignId.c_str());
	if (pCampaignResults == NULL)
	{
		return NULL;
	}

	// There should only be one row matching campaignId
	MySQLRow *pCampaignRow = pCampaignResults->nextRow();
	if (pCampaignRow == NULL)
	{
		delete pCampaignResults;
		return NULL;
	}

	Campaign *pCampaign = new Campaign(pCampaignRow->getColumn(0),
		pCampaignRow->getColumn(1),
		pCampaignRow->getColumn(2));

	delete pCampaignRow;
	delete pCampaignResults;

	return pCampaign;
}

bool CampaignSQL::getCampaigns(const string &criteriaValue, GetCriteria criteriaType,
	unsigned long maxCount, unsigned long startOffset, unsigned long &totalCount,
	set<Campaign> &campaigns)
{
	string::size_type percentPos = string::npos;

	if (m_pDb == NULL)
	{
		return false;
	}

	string fromClause("FROM evaa_emailcampaign");
	switch (criteriaType)
	{
		case STATUS:
			fromClause += " WHERE status='";
			fromClause += m_pDb->escapeString(criteriaValue);
			fromClause += "'";
			break;
		case NAME:
			// Any wildcard ?
			percentPos = criteriaValue.find('%');
			if (percentPos != string::npos)
                        {
				fromClause += " WHERE name LIKE '";
                        }
			else
			{
				fromClause += " WHERE name='";
			}
			fromClause += m_pDb->escapeString(criteriaValue);
			fromClause += "'";
			break;
		case NONE:
		default:
			break;
	}

	string selectSql("SELECT COUNT(*) ");
	selectSql += fromClause;

	// Get the total number of rows matching this, on the first run
	if (startOffset == 0)
	{
		MySQLResults *pCampaignResults = m_pDb->executeStatement(selectSql.c_str());
		if (pCampaignResults != NULL)
		{
			MySQLRow *pCampaignRow = pCampaignResults->nextRow();
			if (pCampaignRow != NULL)
			{
				totalCount = (unsigned long)atol(pCampaignRow->getColumn(0).c_str());

				delete pCampaignRow;
			}

			delete pCampaignResults;
		}
	}

	// Get the actual rows
	// Don't terminate this statement with a semi-colon
	selectSql = "SELECT evaa_emailcampaignid, name, status ";
	selectSql += fromClause;
	selectSql += " ORDER BY evaa_emailcampaignid";

	MySQLResults *pCampaignResults = m_pDb->executeStatement(selectSql,
		startOffset, startOffset + maxCount);
	if ((pCampaignResults == NULL) ||
		(pCampaignResults->getRowsCount() == 0))
	{
		if (pCampaignResults != NULL)
		{
			delete pCampaignResults;
		}

		return false;
	}
	clog << "Got " << pCampaignResults->getRowsCount() << "/" << maxCount << " campaigns" << endl;

	MySQLRow *pCampaignRow = pCampaignResults->nextRow();
	while (pCampaignRow != NULL)
	{
		campaigns.insert(Campaign(pCampaignRow->getColumn(0),
			pCampaignRow->getColumn(1),
			pCampaignRow->getColumn(2)));

		// Next row
		delete pCampaignRow;
		pCampaignRow = pCampaignResults->nextRow();
	}
	delete pCampaignResults;

	return true;
}

bool CampaignSQL::setMessage(const string &campaignId,
	const MessageDetails *pDetails)
{
	if ((m_pDb == NULL) ||
		(campaignId.empty() == true) ||
		(pDetails == NULL))
	{
		return false;
	}

	string updateSql("UPDATE evaa_emailcampaign SET xhtmlcontent='");
	updateSql += m_pDb->escapeString(pDetails->m_htmlContent);
	updateSql += "', xplaincontent='";
	updateSql += m_pDb->escapeString(pDetails->m_plainContent);
	updateSql += "', emailattachment='";
	updateSql += m_pDb->escapeString(pDetails->getAttachmentArray());
	updateSql += "', personalisehtml=";
	if (pDetails->m_personalizeHtml == true)
	{
		updateSql += "1";
	}
	else
	{
		updateSql += "0";
	}
	updateSql += ", personaliseplain=";
	if (pDetails->m_personalizePlain == true)
	{
		updateSql += "1";
	}
	else
	{
		updateSql += "0";
	}
	updateSql += " WHERE evaa_emailcampaignid='";
	updateSql += campaignId;
	updateSql += "';";

	string id;
	return m_pDb->executeSimpleStatement(updateSql, id);
}

MessageDetails *CampaignSQL::getMessage(const string &campaignId)
{
	if ((m_pDb == NULL) ||
		(campaignId.empty() == true))
	{
		return NULL;
	}

	MySQLResults *pCampaignResults = m_pDb->executeStatement("SELECT "
		"xhtmlcontent, xplaincontent, personalisehtml, personaliseplain, "
		"emailattachment, subject, fromname, fromemail, "
		"replyname, replyemail, senderemail, unsublink "
		"FROM evaa_emailcampaign WHERE evaa_emailcampaignid='%s';",
		campaignId.c_str());
	if (pCampaignResults == NULL)
	{
		return NULL;
	}

	// There should only be one row matching campaignId
	MySQLRow *pCampaignRow = pCampaignResults->nextRow();
	if (pCampaignRow == NULL)
	{
		delete pCampaignResults;
		return NULL;
	}

	MessageDetails *pDetails = new MessageDetails();
	pDetails->m_htmlContent = pCampaignRow->getColumn(0);
	pDetails->m_plainContent = pCampaignRow->getColumn(1);
	string personalizeHtml(pCampaignRow->getColumn(2));
	pDetails->m_personalizeHtml = true;
	if (personalizeHtml == "0")
	{
		pDetails->m_personalizeHtml = false;
	}
	string personalizePlain(pCampaignRow->getColumn(3));
	pDetails->m_personalizePlain = true;
	if (personalizePlain == "0")
	{
		pDetails->m_personalizePlain = false;
	}
	pDetails->setAttachmentArray(pCampaignRow->getColumn(4));
	pDetails->m_subject = pCampaignRow->getColumn(5);
	pDetails->m_fromName = pCampaignRow->getColumn(6);
	pDetails->m_fromEmailAddress = pCampaignRow->getColumn(7);
	pDetails->m_replyToName = pCampaignRow->getColumn(8);
	pDetails->m_replyToEmailAddress = pCampaignRow->getColumn(9);
	pDetails->m_senderEmailAddress = pCampaignRow->getColumn(10);
	pDetails->m_unsubscribeLink = pCampaignRow->getColumn(11);
	ConfigurationFile *pConfig = ConfigurationFile::getInstance("");
	if (pConfig != NULL)
	{
		pDetails->m_senderEmailAddress += pConfig->m_senderSuffix;
	}

	delete pCampaignRow;
	delete pCampaignResults;

	return pDetails;
}

bool CampaignSQL::createNewRecipient(const string &campaignId, Recipient &recipient)
{
	if ((m_pDb == NULL) ||
		(campaignId.empty() == true) ||
		(recipient.m_emailAddress.empty() == true) ||
		(recipient.hasValidStatus() == false))
	{
		return false;
	}

	string domainName(getDomainName(recipient.m_emailAddress));
	string insertSql("INSERT INTO evaa_emailrecipient (evaa_emailrecipientid, "
		"evaa_emailcampaignid, name, status, statuscode, emailaddress, "
		"returnpath, domainname, customfield1, customfield2, customfield3, "
		"customfield4, customfield5, customfield6) VALUES(DEFAULT, '");
	insertSql += campaignId;
	insertSql += "', '";
	insertSql += m_pDb->escapeString(recipient.m_name);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(recipient.m_status);
	insertSql += "', '0', '";
	insertSql += m_pDb->escapeString(recipient.m_emailAddress);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(recipient.m_returnPathEmailAddress);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(domainName);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(recipient.m_customFields[1]);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(recipient.m_customFields[2]);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(recipient.m_customFields[3]);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(recipient.m_customFields[4]);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(recipient.m_customFields[5]);
	insertSql += "', '";
	insertSql += m_pDb->escapeString(recipient.m_customFields[6]);
	insertSql += "');";

	if (m_pDb->executeSimpleStatement(insertSql, recipient.m_id) == true)
	{
		return true;
	}

	return false;
}

unsigned long CampaignSQL::listDomains(const string &campaignId,
	const string &status, multimap<unsigned long, string> &domainsBreakdown,
	unsigned long count, unsigned long offset)
{
	if ((m_pDb == NULL) ||
		(campaignId.empty() == true) ||
		(status.empty() == true))
	{
		return 0;
	}

	string selectSql("SELECT domainname, status, COUNT(*) AS recipientscount FROM evaa_emailrecipient WHERE evaa_emailcampaignid='");
	selectSql += campaignId;
	selectSql += "' AND status='";
	selectSql += m_pDb->escapeString(status);
	selectSql += "' GROUP BY domainname, status ORDER BY recipientscount DESC;";

	MySQLResults *pDomainResults = m_pDb->executeStatement(selectSql.c_str());
	if (pDomainResults == NULL)
	{
		return 0;
	}

	MySQLRow *pDomainRow = pDomainResults->nextRow();
	unsigned long rowsCount = pDomainResults->getRowsCount();
	unsigned long domainNum = 0;

	clog << "Campaign has " << rowsCount << " domains" << endl;

	// Sort them by the number of recipients they include
	while (pDomainRow != NULL)
	{
		string domainName(pDomainRow->getColumn(0));
		string domainStatus(pDomainRow->getColumn(1));
		unsigned long domainRecipients = (unsigned long)atol(pDomainRow->getColumn(2).c_str());
		bool goodDomain = false;

		// Make sure the domain name is set
		if (domainName.empty() == false)
		{
			if ((count > 0) &&
				(offset >= 0))
			{
				if ((domainNum >= offset) &&
					(((domainNum - offset) % count) == 0))
				{
					goodDomain = true;
				}
			}
			else
			{
				goodDomain = true;
			}
		}

		if (goodDomain == true)
		{
			clog << "Domain " << domainNum << " " << domainName << ", status " << domainStatus << endl;

			domainsBreakdown.insert(pair<unsigned long, string>(domainRecipients, domainName));
		}

		// Next row
		++domainNum;
		delete pDomainRow;
		pDomainRow = pDomainResults->nextRow();
	}
	delete pDomainResults;

	return rowsCount;
}

Recipient *CampaignSQL::getRecipient(const string &recipientId)
{
	if ((m_pDb == NULL) ||
		(recipientId.empty() == true))
	{
		return NULL;
	}

	MySQLResults *pRecipientResults = m_pDb->executeStatement("SELECT "
		"evaa_emailrecipientid, name, status, emailaddress, returnpath, "
		"customfield1, customfield2, customfield3, customfield4, "
		"customfield5, customfield6 FROM evaa_emailrecipient "
		"WHERE evaa_emailrecipientid='%s';",
		recipientId.c_str());
	if (pRecipientResults == NULL)
	{
		return NULL;
	}

	// There should only be one row matching recipientId
	MySQLRow *pRecipientRow = pRecipientResults->nextRow();
	if (pRecipientRow == NULL)
	{
		delete pRecipientResults;
		return NULL;
	}

	Recipient *pRecipient = new Recipient(pRecipientRow->getColumn(0),
			pRecipientRow->getColumn(1),
			pRecipientRow->getColumn(2),
			pRecipientRow->getColumn(3),
			pRecipientRow->getColumn(4));

	pRecipient->m_customFields[1] = pRecipientRow->getColumn(5);
	pRecipient->m_customFields[2] = pRecipientRow->getColumn(6);
	pRecipient->m_customFields[3] = pRecipientRow->getColumn(7);
	pRecipient->m_customFields[4] = pRecipientRow->getColumn(8);
	pRecipient->m_customFields[5] = pRecipientRow->getColumn(9);
	pRecipient->m_customFields[6] = pRecipientRow->getColumn(10);

	delete pRecipientRow;
	delete pRecipientResults;

	return pRecipient;
}

bool CampaignSQL::getRecipients(const string &campaignId,
	unsigned long maxCount, unsigned long startOffset,
	unsigned long &totalCount, map<string, Recipient> &recipients)
{
	if ((m_pDb == NULL) ||
		(campaignId.empty() == true))
	{
		return false;
	}

	string fromClause("FROM evaa_emailrecipient WHERE evaa_emailcampaignid='");
	fromClause += campaignId;
	fromClause += "'";

	string selectSql("SELECT COUNT(*) ");
	selectSql += fromClause;

	// Get the total number of rows matching this, on the first run
	if (startOffset == 0)
	{
		MySQLResults *pRecipientResults = m_pDb->executeStatement(selectSql.c_str());
		if (pRecipientResults != NULL)
		{
			MySQLRow *pRecipientRow = pRecipientResults->nextRow();
			if (pRecipientRow != NULL)
			{
				totalCount = (unsigned long)atol(pRecipientRow->getColumn(0).c_str());

				delete pRecipientRow;
			}

			delete pRecipientResults;
		}
	}

	// Get the actual rows
	// Don't terminate this statement with a semi-colon
	selectSql = "SELECT evaa_emailrecipientid, name, status, "
		"emailaddress, returnpath, customfield1, customfield2, "
		"customfield3, customfield4, customfield5, customfield6 ";
	selectSql += fromClause;
	selectSql += " ORDER BY evaa_emailrecipientid";

	MySQLResults *pRecipientResults = m_pDb->executeStatement(selectSql,
		startOffset, startOffset + maxCount);
	if ((pRecipientResults == NULL) ||
		(pRecipientResults->getRowsCount() == 0))
	{
		if (pRecipientResults != NULL)
		{
			delete pRecipientResults;
		}

		return false;
	}
	clog << "Got " << pRecipientResults->getRowsCount() << "/" << maxCount << " recipients" << endl;

	MySQLRow *pRecipientRow = pRecipientResults->nextRow();
	while (pRecipientRow != NULL)
	{
		Recipient recipObj(pRecipientRow->getColumn(0),
			pRecipientRow->getColumn(1),
			pRecipientRow->getColumn(2),
			pRecipientRow->getColumn(3),
			pRecipientRow->getColumn(4));

		recipObj.m_customFields[1] = pRecipientRow->getColumn(5);
		recipObj.m_customFields[2] = pRecipientRow->getColumn(6);
		recipObj.m_customFields[3] = pRecipientRow->getColumn(7);
		recipObj.m_customFields[4] = pRecipientRow->getColumn(8);
		recipObj.m_customFields[5] = pRecipientRow->getColumn(9);
		recipObj.m_customFields[6] = pRecipientRow->getColumn(10);

		clog << "Recipient " << recipObj.m_name << " " << recipObj.m_emailAddress
			<< " (" << recipObj.m_id << ")" << endl;

		// Add this to the list of recipients
		recipients[recipObj.m_emailAddress] = recipObj;

		// Next row
		delete pRecipientRow;
		pRecipientRow = pRecipientResults->nextRow();
	}
	delete pRecipientResults;

	return true;
}

bool CampaignSQL::getRecipients(const string &campaignId, const string &status,
	const string &domainName, unsigned long maxCount,
	map<string, Recipient> &recipients)
{
	if ((m_pDb == NULL) ||
		(campaignId.empty() == true))
	{
		return false;
	}

	string fromClause("FROM evaa_emailrecipient WHERE");
	if (status.empty() == false)
	{
		fromClause += " status='";
		fromClause += m_pDb->escapeString(status);
		fromClause += "' AND";
	}
	if (domainName.empty() == false)
	{
		fromClause += " domainName='";
		fromClause += m_pDb->escapeString(domainName);
		fromClause += "' AND";
	}
	fromClause += " evaa_emailcampaignid='";
	fromClause += campaignId;
	fromClause += "'";

	string selectSql("SELECT COUNT(*) ");
	selectSql += fromClause;

	// Get the actual rows
	// Don't terminate this statement with a semi-colon
	selectSql = "SELECT evaa_emailrecipientid, name, status, "
		"emailaddress, returnpath, customfield1, customfield2, "
		"customfield3, customfield4, customfield5, customfield6 ";
	selectSql += fromClause;
	selectSql += " ORDER BY evaa_emailrecipientid";

	MySQLResults *pRecipientResults = m_pDb->executeStatement(selectSql,
		0, maxCount);
	if ((pRecipientResults == NULL) ||
		(pRecipientResults->getRowsCount() == 0))
	{
		if (pRecipientResults != NULL)
		{
			delete pRecipientResults;
		}

		return false;
	}
	clog << "Got " << pRecipientResults->getRowsCount() << "/" << maxCount << " recipients" << endl;

	MySQLRow *pRecipientRow = pRecipientResults->nextRow();
	while (pRecipientRow != NULL)
	{
		Recipient recipObj(pRecipientRow->getColumn(0),
			pRecipientRow->getColumn(1),
			pRecipientRow->getColumn(2),
			pRecipientRow->getColumn(3),
			pRecipientRow->getColumn(4));

		recipObj.m_customFields[1] = pRecipientRow->getColumn(5);
		recipObj.m_customFields[2] = pRecipientRow->getColumn(6);
		recipObj.m_customFields[3] = pRecipientRow->getColumn(7);
		recipObj.m_customFields[4] = pRecipientRow->getColumn(8);
		recipObj.m_customFields[5] = pRecipientRow->getColumn(9);
		recipObj.m_customFields[6] = pRecipientRow->getColumn(10);

		clog << "Recipient " << recipObj.m_name << " " << recipObj.m_emailAddress
			<< " (" << recipObj.m_id << ")" << endl;

		// Add this to the list of recipients
		recipients[recipObj.m_emailAddress] = recipObj;

		// Next row
		delete pRecipientRow;
		pRecipientRow = pRecipientResults->nextRow();
	}
	delete pRecipientResults;

	return true;
}

bool CampaignSQL::setCampaign(const Campaign &campaign)
{
	bool separateColumns = false;

	if ((m_pDb == NULL) ||
		(campaign.m_id.empty() == true))
	{
		return false;
	}

	if ((campaign.m_name.empty() == true) &&
		(campaign.m_status.empty() == true))
	{
		// Nothing to do
		return true;
	}

	string updateSql("UPDATE evaa_emailcampaign SET");
	if (campaign.m_name.empty() == false)
	{
		updateSql += " name='";
		updateSql += m_pDb->escapeString(campaign.m_name);
		updateSql += "'";

		separateColumns = true;
	}
	if (campaign.hasValidStatus() == true)
	{
		if (separateColumns == true)
		{
			updateSql += ",";
		}

		updateSql += " status='";
		updateSql += m_pDb->escapeString(campaign.m_status);
		updateSql += "'";
	}
	updateSql += " WHERE evaa_emailcampaignid='";
	updateSql += campaign.m_id;
	updateSql += "';";

	string id;
	return m_pDb->executeSimpleStatement(updateSql, id);
}

bool CampaignSQL::setRecipient(Recipient &recipient)
{
	bool separateColumns = false;

	if ((m_pDb == NULL) ||
		(recipient.m_id.empty() == true))
	{
		return false;
	}

	if ((recipient.m_name.empty() == true) &&
		(recipient.m_status.empty() == true) &&
		(recipient.m_emailAddress.empty() == true) &&
		(recipient.m_returnPathEmailAddress.empty() == true) &&
		(recipient.m_customFields.empty() == true))
	{
		// Nothing to do
		return true;
	}

	string domainName(getDomainName(recipient.m_emailAddress));
	string updateSql("UPDATE evaa_emailrecipient SET");
	if (recipient.m_name.empty() == false)
	{
		updateSql += " name='";
		updateSql += m_pDb->escapeString(recipient.m_name);
		updateSql += "'";

		separateColumns = true;
	}
	if (recipient.hasValidStatus() == true)
	{
		if (separateColumns == true)
		{
			updateSql += ",";
		}

		updateSql += " status='";
		updateSql += m_pDb->escapeString(recipient.m_status);
		updateSql += "'";

		separateColumns = true;
	}
	if (recipient.m_emailAddress.empty() == false)
	{
		if (separateColumns == true)
		{
			updateSql += ",";
		}

		updateSql += " emailaddress='";
		updateSql += m_pDb->escapeString(recipient.m_emailAddress);
		updateSql += "'";

		separateColumns = true;
	}
	if (recipient.m_returnPathEmailAddress.empty() == false)
	{
		if (separateColumns == true)
		{
			updateSql += ",";
		}

		updateSql += " returnpath='";
		updateSql += m_pDb->escapeString(recipient.m_returnPathEmailAddress);
		updateSql += "', domainname='";
		updateSql += m_pDb->escapeString(domainName);
		updateSql += "'";

		separateColumns = true;
	}
	if (recipient.m_customFields.empty() == false)
	{
		if (separateColumns == true)
		{
			updateSql += ",";
		}

		updateSql += " customfield1='";
		updateSql += m_pDb->escapeString(recipient.m_customFields[1]);
		updateSql += "', customfield2='";
		updateSql += m_pDb->escapeString(recipient.m_customFields[2]);
		updateSql += "', customfield3='";
		updateSql += m_pDb->escapeString(recipient.m_customFields[3]);
		updateSql += "', customfield4='";
		updateSql += m_pDb->escapeString(recipient.m_customFields[4]);
		updateSql += "', customfield5='";
		updateSql += m_pDb->escapeString(recipient.m_customFields[5]);
		updateSql += "', customfield6='";
		updateSql += m_pDb->escapeString(recipient.m_customFields[6]);
		updateSql += "'";
	}
	updateSql += " WHERE evaa_emailrecipientid='";
	updateSql += recipient.m_id;
	updateSql += "';";

	string id;
	return m_pDb->executeSimpleStatement(updateSql, id);
}

bool CampaignSQL::setRecipientsStatus(const string &campaignId, const string &status)
{
	if ((m_pDb == NULL) ||
		(campaignId.empty() == true))
	{
		return false;
	}

	string updateSql("UPDATE evaa_emailrecipient SET status='");
	updateSql += m_pDb->escapeString(status);
	updateSql += "' WHERE evaa_emailcampaignid='";
	updateSql += campaignId;
	updateSql += "';";

	string id;
	return m_pDb->executeSimpleStatement(updateSql, id);
}

bool CampaignSQL::deleteRecipient(const string &recipientId)
{
	bool deletionStatus = true;

	if ((m_pDb == NULL) ||
		(recipientId.empty() == true))
	{
		return false;
	}

	string deleteSql("DELETE FROM evaa_emailrecipient WHERE evaa_emailrecipientid='");
	deleteSql += recipientId;
	deleteSql += "';";

	string id;
	if (m_pDb->executeSimpleStatement(deleteSql, id) == false)
	{
		deletionStatus = false;
	}

	return deletionStatus;
}

bool CampaignSQL::deleteCampaign(const string &campaignId)
{
	bool deletionStatus = true;

	if ((m_pDb == NULL) ||
		(campaignId.empty() == true))
	{
		return false;
	}

	string deleteSql("DELETE FROM evaa_emailrecipient WHERE evaa_emailcampaignid='");
	deleteSql += campaignId;
	deleteSql += "';";

	string id;
	if (m_pDb->executeSimpleStatement(deleteSql, id) == false)
	{
		deletionStatus = false;
	}

	deleteSql = "DELETE FROM evaa_emailcampaign WHERE evaa_emailcampaignid='";
	deleteSql += campaignId;
	deleteSql += "';";

	if (m_pDb->executeSimpleStatement(deleteSql, id) == false)
	{
		deletionStatus = false;
	}

	return deletionStatus;
}

